'use client';

import { useState } from 'react';
import Image from 'next/image';
import { BSCToken } from '@/types/bsc';
import { formatBNB, formatNumber } from '@/utils/format';

interface BSCTokenListProps {
  tokens: BSCToken[];
  onTokenSelect: (token: BSCToken) => void;
  loading?: boolean;
}

// 格式化时间为相对时间
const formatTimeAgo = (timestamp: number): string => {
  const now = Date.now();
  const diff = now - (timestamp * 1000);
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);

  if (days > 0) return `${days}天前`;
  if (hours > 0) return `${hours}小时前`;
  if (minutes > 0) return `${minutes}分钟前`;
  return '刚刚';
};

interface BSCTokenListProps {
  tokens: BSCToken[];
  onTokenSelect: (token: BSCToken) => void;
  loading?: boolean;
}

export function BSCTokenList({ tokens, onTokenSelect, loading }: BSCTokenListProps) {
  const [sortBy, setSortBy] = useState<'newest' | 'price' | 'volume' | 'market_cap'>('newest');
  const [filter, setFilter] = useState<'all' | 'active' | 'launched'>('all');

  console.log('BSCTokenList received tokens:', tokens);
  console.log('BSCTokenList tokens length:', tokens?.length);

  const filteredTokens = tokens.filter(token => {
    if (filter === 'active') return !token.launched && !token.cancelled;
    if (filter === 'launched') return token.launched;
    return true;
  });

  const sortedTokens = [...filteredTokens].sort((a, b) => {
    switch (sortBy) {
      case 'newest':
        return b.createdAt - a.createdAt;
      case 'price':
        return parseFloat(b.currentPrice) - parseFloat(a.currentPrice);
      case 'volume':
        return parseFloat(b.volume24h || '0') - parseFloat(a.volume24h || '0');
      case 'market_cap':
        return parseFloat(b.marketCap || '0') - parseFloat(a.marketCap || '0');
      default:
        return 0;
    }
  });

  if (loading) {
    return (
      <div className="flex justify-center py-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Filters */}
      <div className="space-y-3 w-full px-6 md:px-12 lg:px-[50px]">
        <div className="flex gap-2 justify-center">
          <select
            value={filter}
            onChange={(e) => setFilter(e.target.value as 'all' | 'active' | 'launched')}
            className="pixel-input"
          >
            <option value="all">all</option>
            <option value="active">active</option>
            <option value="launched">launched</option>
          </select>

          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value as 'newest' | 'price' | 'volume' | 'market_cap')}
            className="pixel-input"
          >
            <option value="newest">new</option>
            <option value="price">price</option>
            <option value="volume">volume</option>
            <option value="market_cap">market cap</option>
          </select>
        </div>
      </div>

      {/* Token Grid */}
      {sortedTokens.length === 0 ? (
        <div className="text-center py-12 text-gray-400">
          <div className="text-gray-400 mb-4">
            <svg
              className="w-12 h-12 mx-auto"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
              />
            </svg>
          </div>
          <p className="text-gray-400">No tokens available</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 w-full">
          {sortedTokens.map((token) => (
            <div
              key={token.id}
              className="pixel-card transition-transform hover:scale-105 relative cursor-pointer"
              onClick={() => onTokenSelect(token)}
            >
              {/* Token Header */}
              <div className="flex items-center space-x-3 mb-4">
                {token.imageUrl ? (
                  <Image
                    src={token.imageUrl}
                    alt={token.name}
                    width={48}
                    height={48}
                    className="rounded-full object-cover"
                  />
                ) : (
                  <div className="w-12 h-12 bg-gradient-to-br from-purple-400 to-purple-600 flex items-center justify-center" style={{imageRendering: 'pixelated'}}>
                    <span className="text-white font-bold text-lg">
                      {token.symbol.charAt(0)}
                    </span>
                  </div>
                )}

                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <h3 className="font-semibold truncate font-body">
                      {token.name}
                    </h3>
                    {token.launched && (
                      <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-yellow-400 text-black border-2 border-black">
                        🎓 Launched
                      </span>
                    )}
                    {token.cancelled && (
                      <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-red-400 text-black border-2 border-black">
                        ❌ Cancelled
                      </span>
                    )}
                  </div>
                  <p className="text-xs text-gray-400 font-mono">{token.symbol}</p>
                </div>
              </div>

              {/* Token Stats */}
              <div className="space-y-2 mb-4">
                <div className="flex justify-between">
                  <span className="text-xs text-gray-400">price</span>
                  <span className="text-sm font-medium">
                    {formatBNB(token.currentPrice)} BNB
                  </span>
                </div>

                <div className="flex justify-between">
                  <span className="text-xs text-gray-400">TVL</span>
                  <span className="text-sm font-medium">
                    {token.marketCap ? `$${formatNumber(parseFloat(token.marketCap))}` : '$0'}
                  </span>
                </div>

                <div className="flex justify-between">
                  <span className="text-xs text-gray-400">Holder</span>
                  <span className="text-sm font-medium">
                    {token.holders ? formatNumber(token.holders) : '0'}
                  </span>
                </div>

                {token.priceChange24h !== undefined && token.priceChange24h !== null && (
                  <div className="flex justify-between">
                    <span className="text-xs text-gray-400">24h</span>
                    <span className={`text-sm font-medium ${
                      token.priceChange24h >= 0 ? 'text-green-400' : 'text-red-400'
                    }`}>
                      {token.priceChange24h >= 0 ? '+' : ''}
                      {token.priceChange24h.toFixed(2)}%
                    </span>
                  </div>
                )}
              </div>

              {/* Progress Bar for Pre-sale */}
              {!token.launched && !token.cancelled && (
                <div className="mb-4">
                  <div className="flex justify-between text-xs text-gray-400 mb-1">
                    <span>Fundraising Progress</span>
                    <span>
                      {((parseFloat(token.raisedAmount) / parseFloat(token.targetAmount)) * 100).toFixed(1)}%
                    </span>
                  </div>
                  <div className="w-full bg-gray-700 rounded-full h-2">
                    <div
                      className="bg-purple-600 h-2 rounded-full transition-all duration-300"
                      style={{
                        width: `${Math.min(
                          (parseFloat(token.raisedAmount) / parseFloat(token.targetAmount)) * 100,
                          100
                        )}%`
                      }}
                    ></div>
                  </div>
                </div>
              )}

              {/* Description */}
              {token.description && (
                <p className="text-sm text-gray-300 mb-4 line-clamp-2 font-body">
                  {token.description}
                </p>
              )}

              {/* Footer */}
              <div className="flex items-center justify-between text-xs text-gray-400">
                <span>Created {formatTimeAgo(token.createdAt)}</span>
                <span className="font-mono text-xs bg-gray-700 px-2 py-1 border border-gray-600">
                  {`${token.tokenAddress.slice(0, 4)}...${token.tokenAddress.slice(-4)}`}
                </span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
